package com.example.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.web.bind.annotation.InitBinder;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Configuration
@EnableConfigurationProperties(ESExtendProperties.class)
public class ESConfig {

    @Autowired
    ElasticsearchRestClientProperties esProperties;

    @Autowired
    ESExtendProperties esExtendProperties;

    /**
     * 注册es客户端，来进行一切es操作
     * @return
     */
    @Bean("customRestHighLevelClient")
    public RestHighLevelClient createSimpleClient(){
//        String[] hosts = esExtendProperties.getHosts();
//        HttpHost[] httpHosts= Arrays.stream(hosts).map(
//                host->{
//                    String[] hostParts=host.split(":");
//                    String hostName=hostParts[0];
//                    int port= Integer.parseInt(hostParts[1]);
//                    return new HttpHost(hostName,port,HttpHost.DEFAULT_SCHEME_NAME);
//                }
//        ).filter(Objects::nonNull).toArray(HttpHost[]::new);
        //配置多个主节点地址，但某一节点宕机，会自动切换到另一节点地址去进行操作。
        List<ESExtendProperties.Server> servers = esExtendProperties.getServers();
        HttpHost[] httpHosts = servers.stream().map(
                server -> {
                    return new HttpHost(server.getHostIp(), server.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
                }
        ).filter(Objects::nonNull).toArray(HttpHost[]::new);
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }

}
